#!/bin/bash

# 配置变量
DOMAIN_OR_IP="your_domain_or_ip"  # 替换为你的域名或IP地址
CONFIG_FILE="/etc/nginx/sites-available/filebox"
SSL_DIR="/etc/ssl"
SELF_SIGNED_CERT="${SSL_DIR}/certs/nginx-selfsigned.crt"
SELF_SIGNED_KEY="${SSL_DIR}/private/nginx-selfsigned.key"

# 检查证书是否即将过期（30天内）
check_cert_expiry() {
    local cert_file=$1
    local expiry_date=$(openssl x509 -enddate -noout -in "$cert_file" | cut -d= -f2)
    local expiry_epoch=$(date -d "$expiry_date" +%s)
    local now_epoch=$(date +%s)
    local days_until_expiry=$(( (expiry_epoch - now_epoch) / 86400 ))

    if [ "$days_until_expiry" -lt 30 ]; then
        return 0  # 证书即将过期
    else
        return 1  # 证书未过期
    fi
}

# 更新自签名证书
update_self_signed_cert() {
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
        -keyout "$SELF_SIGNED_KEY" \
        -out "$SELF_SIGNED_CERT" \
        -subj "/CN=${DOMAIN_OR_IP}"
    systemctl restart nginx
}

# 更新Let's Encrypt证书
update_letsencrypt_cert() {
    certbot renew --non-interactive --post-hook "systemctl restart nginx"
}

# 主逻辑
if [[ $DOMAIN_OR_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    # 自签名证书
    if check_cert_expiry "$SELF_SIGNED_CERT"; then
        echo "自签名证书即将过期，正在更新..."
        update_self_signed_cert
    else
        echo "自签名证书未过期，无需更新。"
    fi
else
    # Let's Encrypt证书
    if check_cert_expiry "/etc/letsencrypt/live/${DOMAIN_OR_IP}/fullchain.pem"; then
        echo "Let's Encrypt证书即将过期，正在更新..."
        update_letsencrypt_cert
    else
        echo "Let's Encrypt证书未过期，无需更新。"
    fi
fi